package com.main.sales.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.main.sales.common.R;
import com.main.sales.dto.DishDto;
import com.main.sales.pojo.Category;
import com.main.sales.pojo.Dish;
import com.main.sales.pojo.DishFlavor;
import com.main.sales.service.CategoryService;
import com.main.sales.service.DishFlavorService;
import com.main.sales.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        log.info("dishDto：{}", dishDto);
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");

    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> list(int page, int pageSize, String name) {
        log.info("page{},pageSize{},name{}", page, pageSize, name);
        //1.构造分页器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //1、
        Page<DishDto> dishDtoPage = new Page<>();
        //2.条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //3.添加过滤条件
        lqw.like(Strings.isNotEmpty(name), Dish::getName, name);
        //4.添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);
        //5.执行查询
        dishService.page(pageInfo, lqw);

        //2、对象拷贝，忽略数据拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        log.info("分页查询1：{}", pageInfo.getRecords());
        log.info("分页查询2：{}", dishDtoPage.getRecords());
        //3、获取数据
        List<Dish> records = pageInfo.getRecords();

        //4、给数据 赋值 菜品分类名称
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将数据赋值给dishDto
            BeanUtils.copyProperties(item, dishDto);
            //获取菜品分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //获取菜品分类名称
                String categoryName = category.getName();
                //将菜品分类名称赋值到dishDto中
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        //5、赋值数据到dishDto中
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 回显 根据id查询菜品信息和对应口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        if (dishService.getByIdWithFlavor(id) != null)
            return R.success(dishService.getByIdWithFlavor(id));

        return R.error("没有查询到对应菜品信息");
    }

    /**
     * 根据id更改菜品信息
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //清理所有缓存
        /*Set keys = redisTemplate.keys("dish_");
        redisTemplate.delete(keys);*/
        //精确清理
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
        return R.success("菜品信息修改成功");
    }

    /**
     * 新建套餐管理 回显 菜品名称
     *
     * @param dish
     * @return
     */
/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        List<Dish> list = null;
        if (dish.getCategoryId() != null) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getCategoryId, dish.getCategoryId());
            lqw.eq(Dish::getStatus, 1);
            lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            list = dishService.list(lqw);
        }
        if (dish.getName() != null) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getStatus, 1);
            lqw.like(Dish::getName, dish.getName());
            list = dishService.list(lqw);
        }
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> list = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //1、先从Redis中 获取缓存数据
        list = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //2、如果存在，直接返回，无需查询数据库
        if (list != null) {
            return R.success(list);
        }

        if (dish.getCategoryId() != null) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getCategoryId, dish.getCategoryId());
            lqw.eq(Dish::getStatus, 1);
            lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            List<Dish> dishList = dishService.list(lqw);

            list = dishList.stream().map((item) -> {
                DishDto dishDto = new DishDto();
                //将数据赋值给dishDto
                BeanUtils.copyProperties(item, dishDto);
                //获取菜品分类id
                Long categoryId = item.getCategoryId();
                //根据id查询分类对象
                Category category = categoryService.getById(categoryId);
                if (category != null) {
                    //获取菜品分类名称
                    String categoryName = category.getName();
                    //将菜品分类名称赋值到dishDto中
                    dishDto.setCategoryName(categoryName);
                }
                //当前菜品id
                Long dishId = item.getId();
                LambdaQueryWrapper<DishFlavor> dfLQW = new LambdaQueryWrapper<>();
                dfLQW.eq(DishFlavor::getDishId, dishId);
                List<DishFlavor> dishFlavorList = dishFlavorService.list(dfLQW);//口味集合
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            }).collect(Collectors.toList());

        }

        if (dish.getName() != null) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getStatus, 1);
            lqw.like(Dish::getName, dish.getName());
            List<Dish> dishList = dishService.list(lqw);
            BeanUtils.copyProperties(dishList, list);
        }
        //3、如果不存在，需要查询数据库，将查询到的数据缓存到Redis中
        redisTemplate.opsForValue().set(key, list, 60, TimeUnit.MINUTES);
        return R.success(list);
    }

    /**
     * 根据id删除菜品信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(String ids) {
        String[] id = ids.split(",");
        for (String s : id) {
            dishService.removeById(s);
        }
        return R.success("删除成功");
    }

    /**
     * 根据id更改菜品信息
     *
     * @param id
     * @return
     */
    @PostMapping("/status")
    public R<String> update(String id, int status) {
//        log.info("根据id更改菜品信息：{}", id);
//        log.info("根据id更改菜品信息：{}", status);
        String[] ids = id.split(",");
        Dish dish = new Dish();
        dish.setStatus(status);
        for (String s : ids) {
            dish.setId(Long.parseLong(s));
//            log.info("根据id更改菜品信息：{}", s);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }
}
